import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by lanouhn on 17/7/18.
 */
public class test1{
    public  static void main(String[]  args)
    {
        String myUrl="http://img.ivsky.com/img/tupian/pre/201707/02/hubo-009.jpg";
        HttpURLConnection connection =null;
        InputStream is=null;//输入流，接受网络请求结果
        try {
            URL url=new URL(myUrl);

            connection = (HttpURLConnection) url.openConnection();

            int code =connection.getResponseCode();

            if(code  == 200)
            {
                is=connection.getInputStream();//读取输入流，将结果转换为String
                //按行读
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
            byte [] result= new byte[200*1024];
                StringBuffer  sb= new StringBuffer();
                result =readStream(is);



                System.out.println(result);


                //存储结果，并存在桌面txt


                String path="//Users/lanouhn/Desktop/hello/22.jpg ";
                File file=new File(path);
                FileOutputStream fos=new FileOutputStream(file);
                fos.write(result);


            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch(IOException e)
        {
            e.printStackTrace();
        }finally
        {
            if(connection!=null)
            {
                connection.disconnect();
            }
            if(is !=null)
            {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static byte[] readStream(InputStream inStream) throws IOException {


        ByteArrayOutputStream outSteam=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];
        int len =-1;
        while((len=inStream.read(buffer))!=-1)
        {
           outSteam.write(buffer,0,len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();


    }

}
